package com.example.anni.zhuzhoujia.bogege;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.lhh.ptrrv.library.PullToRefreshRecyclerView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 张钧博 on 2016/6/23.
 */
public class CommentActivity extends AppCompatActivity {
    private PullToRefreshRecyclerView mPtrrv;
    private List<Map<String, String>> commentList;
    private static final int DEFAULT_ITEM_SIZE = 10;
    private static final int ITEM_SIZE_OFFSET = 5;
    private static final int MSG_CODE_REFRESH = 0;
    private static final int MSG_CODE_LOADMORE = 1;
    private String newsId;

    private EditText sendMyCommment;
    private TextView tvSendComment;
    private ImageView ivTotalCommentBack;
    private String evText;

    private static final int TIME = 1000;
    private TotalCommentAdapter mAdapter;
    JSONArray datas;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comment_main);
        Log.e("onCreate", "onCreate");

        readDate();
        initView();
        //mAdapter.setCount(DEFAULT_ITEM_SIZE);
        tvSendComment = (TextView) findViewById(R.id.tv_send_comment);
        sendMyCommment = (EditText) findViewById(R.id.sendmycomment);
        tvSendComment.setOnClickListener(new SendCommentListener());
        ivTotalCommentBack = (ImageView) findViewById(R.id.total_comment_back);
        ivTotalCommentBack.setOnClickListener(TotalCommentBack);
        sendMyCommment.setOnClickListener(new SendMyCommentOnClickListener());

    }

    private void initView() {
        Log.e("initView", "initView");
        mPtrrv = (PullToRefreshRecyclerView) findViewById(R.id.ptr_lv_comment);
        mPtrrv.setSwipeEnable(true);
        //加载条
        DemoLoadMoreView loadMoreView = new DemoLoadMoreView(this, mPtrrv.getRecyclerView());
        loadMoreView.setLoadmoreString("加载中...");
        loadMoreView.setLoadMorePadding(100);
        // set the layoutManager which to use
        //mPtrrv.setLayoutManager(new LinearLayoutManager(this));
        //线性管理器
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mPtrrv.setLayoutManager(layoutManager);
        mPtrrv.setPagingableListener(new PullToRefreshRecyclerView.PagingableListener() {
            @Override
            public void onLoadMoreItems() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_LOADMORE, TIME);
            }
        });
        mPtrrv.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessageDelayed(MSG_CODE_REFRESH, TIME);
            }
        });
        //设置下划线
        /*mPtrrv.getRecyclerView().addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));*/
        //设置动画
        mPtrrv.getRecyclerView().setItemAnimator(new DefaultItemAnimator());
        mPtrrv.addHeaderView(View.inflate(this, R.layout.read_history_header, null));
        mPtrrv.setEmptyView(View.inflate(this, R.layout.read_history_empty_view, null));
        mPtrrv.removeHeader();
        mPtrrv.setLoadMoreFooter(loadMoreView);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_CODE_REFRESH) {
                readDate();
                mPtrrv.setOnRefreshComplete();
            } else if (msg.what == MSG_CODE_LOADMORE) {
                if (datas.size() - mAdapter.getItemCount() >= 5) {
                    mAdapter.setCount(mAdapter.getItemCount() + ITEM_SIZE_OFFSET);
                    mPtrrv.onFinishLoading(true, false);
                } else if (datas.size() - mAdapter.getItemCount() < 5 && datas.size() - mAdapter.getItemCount() > 0) {
                    mAdapter.setCount(mAdapter.getItemCount() + datas.size() - mAdapter.getItemCount());
                    Log.e("mAdapter", mAdapter.getItemCount() + datas.size() - mAdapter.getItemCount() + "");
                    mPtrrv.onFinishLoading(true, false);
                } else if (datas.size() - mAdapter.getItemCount() < 0) {
                    mAdapter.setCount(datas.size());
                } else {
                    //Log.e("mAdapter", "没有更多加载"+"");
                    //over
                    Toast.makeText(CommentActivity.this, "没有更多加载", Toast.LENGTH_SHORT).show();
                    mPtrrv.onFinishLoading(false, false);
                }
            }
        }
    };
    /**
     * 读取数据
     */
    private void readDate() {
        Log.e("readDate", "readDate");
        commentList = new ArrayList<>();
        RequestParams params = new RequestParams
                ("http://tr.zzapi.gson.cn/api/comment/list");
        newsId = getIntent().getStringExtra("newsId");
        params.addQueryStringParameter("newsId", newsId);
        params.addQueryStringParameter("page", "1");
        params.addQueryStringParameter("rows", "30");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String s) {

                JSONObject jsonobject = JSON.parseObject(s);
                datas = jsonobject.getJSONArray("data");
                for (int j = 0; j < datas.size(); j++) {

                    Map<String, String> commentMap = new HashMap<String, String>();
                    JSONObject comment = datas.getJSONObject(j);

                    String commentContent = comment.getString("content");
                    String commentDateline = (String) comment.get("dateline");

                    JSONObject commentUser = JSON.parseObject(comment.getString("user"));
                    if (commentUser != null) {
                        String area = commentUser.getString("area");
                        String avatar = commentUser.getString("avatar");
                        String commentNickName = commentUser.getString("nickName");
                        String commentGenter = commentUser.getString("gender");

                        commentMap.put("area", area);
                        commentMap.put("avatar", avatar);
                        commentMap.put("commentNickName", commentNickName);
                        commentMap.put("commentGenter", commentGenter);
                    } else if (commentUser == null) {
                        commentMap.put("area", null);
                        commentMap.put("avatar", null);
                        commentMap.put("commentNickName", null);
                        commentMap.put("commentGenter", "");
                    }
                    commentMap.put("commentContent", commentContent);
                    commentMap.put("commentDateline", commentDateline);
                    commentList.add(commentMap);
                }
                mAdapter = new TotalCommentAdapter(CommentActivity.this, commentList);
                if (datas.size() < 10) {
                    mAdapter.setCount(datas.size());
                } else {
                    mAdapter.setCount(DEFAULT_ITEM_SIZE);
                }
                mPtrrv.setAdapter(mAdapter);
                mPtrrv.onFinishLoading(true, false);



            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                Toast.makeText(CommentActivity.this, "完成了", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {
                //Toast.makeText(CommentActivity.this, "完成了", Toast.LENGTH_SHORT).show();
            }
        });
    }

    class TotalCommentAdapter extends RecyclerView.Adapter<MyViewHolder> {
        private List<Map<String, String>> commentList;
        private Context mContext;
        private LayoutInflater mInflater;
        protected int mCount = 0;

        public void setCount(int count) {
            this.mCount = count;
        }

        public TotalCommentAdapter(Context mContext, List<Map<String, String>> commentList) {
            this.commentList = commentList;
            this.mContext = mContext;
            mInflater = LayoutInflater.from(mContext);
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.see_news_comment_listview_item, parent, false);
            MyViewHolder holder = new MyViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            ImageOptions avatarOptions = new ImageOptions.Builder()
                    .setCircular(true)
                    .setLoadingDrawableId(R.mipmap.ic_launcher)
                    .setFailureDrawableId(R.mipmap.default_avatar)
                    .build();
            x.image().bind(holder.newsCommentAvatar,
                    "http://tr.zzapi.gson.cn/" + commentList.get(position).get("cover"),
                    avatarOptions);
            holder.newsCommentNickname.setText(commentList.get(position).get("commentNickName"));
            if (commentList.get(position).get("commentGenter").equals("BOY")) {
                holder.newsCommentSex.setImageResource(R.mipmap.girl);
            } else if (commentList.get(position).get("commentGenter").equals("GIRL")) {
                holder.newsCommentSex.setImageResource(R.mipmap.boy);
            }
            holder.newsCommentTime.setText(commentList.get(position).get("commentDateline"));
            holder.newsCommentContent.setText(commentList.get(position).get("commentContent"));
            holder.newsCommentArea.setText(commentList.get(position).get("area"));
        }

        @Override
        public int getItemCount() {
            return mCount;
        }

    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        public ImageView newsCommentAvatar;
        public TextView newsCommentNickname;
        public ImageView newsCommentSex;
        public ImageView good;
        public TextView newsCommentGoodNumber;
        public ImageView bad;
        public TextView newsCommentBadNumber;
        public TextView newsCommentTime;
        public TextView newsCommentContent;
        public TextView newsCommentArea;

        public MyViewHolder(View view) {
            super(view);
            newsCommentAvatar = (ImageView) view.findViewById(R.id.news_comment_avatar);
            newsCommentNickname = (TextView) view.findViewById(R.id.news_comment_username);
            newsCommentSex = (ImageView) view.findViewById(R.id.news_comment_sex);
            good = (ImageView) view.findViewById(R.id.news_comment_good);
            newsCommentTime = (TextView) view.findViewById(R.id.news_comment_time);
            newsCommentContent = (TextView) view.findViewById(R.id.news_comment_content);
            newsCommentArea = (TextView) view.findViewById(R.id.news_comment_area);
        }

    }

    /**
     * 发表评论
     */
    private class SendCommentListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            RequestParams params2 = new RequestParams("http://tr.zzapi.gson.cn/api/comment/comment");
            evText = String.valueOf(sendMyCommment.getText());

            if (evText.length() >= 2) {
                params2.addBodyParameter("newsId", newsId);
                params2.addBodyParameter("content", evText);
                x.http().post(params2, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Toast.makeText(CommentActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                        //tvSendComment.setVisibility(View.GONE);
                        sendMyCommment.setText("");
                        sendMyCommment.setHint("我来说两句...");
                        View view = getWindow().peekDecorView();
                        InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);

                    }

                    @Override
                    public void onError(Throwable throwable, boolean b) {

                    }

                    @Override
                    public void onCancelled(CancelledException e) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            } else {
                Toast.makeText(CommentActivity.this, "内容不得少于两个字", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 返回按钮的监听  直接创建对象，不用创建类。
     */
    View.OnClickListener TotalCommentBack = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    };

    /**
     * 物理返回键的监听
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            if (!(sendMyCommment.getText().length() == 0)) {
                sendMyCommment.setSelected(false);
                evText = String.valueOf(sendMyCommment.getText());
                sendMyCommment.setText("");
                sendMyCommment.setHint("我来说两句...");
                //Toast.makeText(SeeNewsActivity.this, sendMyComment.getText(), Toast.LENGTH_SHORT).show();

                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * edittext监听器
     */
    private class SendMyCommentOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            sendMyCommment.setText(evText);
        }
    }

}
